const { getApiUrl } = require('../../config/config')
const { formatTime, formatDate } = require('../../utils/util')

Page({
  data: {
    comments: [],
    days: 'null', // 默认查询全部历史数据
    pageSize: 10,
    currentPage: 1,
    isLoading: false,
    hasMore: true,
    totalComments: 0,
    userId: null,
    dayOptions: [
      { value: 'null', text: '全部' },
      { value: '7', text: '最近7天' },
      { value: '30', text: '最近30天' },
      { value: '90', text: '最近90天' }
    ],
    showFilter: false,
    dayFilterText: '全部',
    showBackToTop: false,
    scrollTop: 0
  },

  onLoad: function() {
    // 设置导航栏
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#ff6b6b'
    });
    
    // 获取用户ID并加载数据
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({ userId: userInfo.id });
      this.fetchComments();
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.redirectTo({ url: '/pages/login/login' });
          }, 1500);
        }
      });
    }

    // 创建页面滚动监听器
    this.createIntersectionObserver()
      .relativeToViewport()
      .observe('.comment-item', (res) => {
        // 为出现在视图中的元素添加动画
        if (res.intersectionRatio > 0 && res.dataset) {
          const index = res.dataset.index;
          if (index !== undefined) {
            const animation = wx.createAnimation({
              duration: 500,
              timingFunction: 'ease-out',
            });
            animation.opacity(1).translateY(0).step();
            
            this.setData({
              [`comments[${index}].animation`]: animation.export()
            });
          }
        }
      });
  },

  onShow: function() {
    // 如果需要重新加载
    if (this.data.needRefresh) {
      this.resetAndFetch();
      this.setData({ needRefresh: false });
    }
  },

  onPullDownRefresh: function() {
    this.resetAndFetch();
    
    setTimeout(() => {
      wx.stopPullDownRefresh();
      
      // 显示成功提示
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 1500
      });
    }, 1000);
  },

  onReachBottom: function() {
    if (this.data.hasMore && !this.data.isLoading) {
      this.loadMoreData();
    }
  },

  // 页面点击事件处理
  onPageTap: function() {
    // 点击页面空白区域时关闭筛选下拉框
    if (this.data.showFilter) {
      this.setData({ showFilter: false });
    }
  },

  // 监听页面滚动事件
  onPageScroll: function(e) {
    this.setData({
      scrollTop: e.scrollTop,
      showBackToTop: e.scrollTop > 300
    });
  },

  // 回到顶部
  scrollToTop: function() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
    
    if (wx.vibrateShort) {
      wx.vibrateShort({ type: 'light' });
    }
  },

  // 显示/隐藏筛选选项
  toggleFilter: function(e) {
    this.setData({
      showFilter: !this.data.showFilter
    });
    
    if (wx.vibrateShort) {
      wx.vibrateShort({ type: 'light' });
    }
    
    // 只在事件对象存在时调用 stopPropagation
    if (e && e.stopPropagation) {
      e.stopPropagation();
    }
  },

  // 选择天数筛选
  selectDayFilter: function(e) {
    const { value, text } = e.currentTarget.dataset;
    if (value === this.data.days) {
      this.setData({ showFilter: false });
      return;
    }
    
    this.setData({
      days: value,
      dayFilterText: text,
      showFilter: false
    });
    
    // 添加触感反馈
    if (wx.vibrateShort) {
      wx.vibrateShort({ type: 'light' });
    }
    
    // 重置并重新加载数据
    this.resetAndFetch();
  },

  // 重置并重新加载数据
  resetAndFetch: function() {
    this.setData({
      currentPage: 1,
      hasMore: true,
      comments: [],
      totalComments: 0
    });
    this.fetchComments();
  },

  // 加载更多数据
  loadMoreData: function() {
    if (!this.data.hasMore || this.data.isLoading) return;
    
    const nextPage = this.data.currentPage + 1;
    this.setData({ currentPage: nextPage });
    this.fetchComments();
  },

  // 获取评论数据
  fetchComments: function() {
    const { userId, days, currentPage, pageSize } = this.data;

    if (!userId) return;

    this.setData({ isLoading: true });

    wx.request({
      url: getApiUrl('/message/recent-comments'),
      method: 'GET',
      data: {
        userId: userId,
        days: days === 'null' ? null : days,
        page: currentPage,
        size: pageSize
      },
      success: (res) => {
        if (res.data.code === 200) {
          const newData = res.data.data;
          
          // 处理日期显示和状态
          if (newData.comments && newData.comments.length > 0) {
            newData.comments.forEach((item, index) => {
              item.formattedTime = this.getSimpleDate(item.createTime);
              
              // 初始化点赞状态
              item.isLiked = false;
              
              // 准备动画属性
              const animation = wx.createAnimation({
                duration: 500,
                timingFunction: 'ease-out',
                delay: index * 50
              });
              animation.opacity(0).translateY(30).step({ duration: 0 });
              item.animation = animation.export();
            });
          }
          
          // 合并数据
          let updatedComments;
          if (this.data.currentPage === 1) {
            // 首次加载
            updatedComments = newData.comments || [];
          } else {
            // 加载更多，合并数据
            updatedComments = [...this.data.comments, ...(newData.comments || [])];
          }
          
          // 检查是否还有更多数据可加载
          const hasMore = newData.comments && newData.comments.length === pageSize;
          
          this.setData({
            comments: updatedComments,
            totalComments: newData.total || 0,
            hasMore: hasMore
          });
          
          // 延迟添加入场动画
          setTimeout(() => {
            updatedComments.forEach((item, index) => {
              const animation = wx.createAnimation({
                duration: 500,
                timingFunction: 'ease-out',
                delay: index % pageSize * 50  // 只对新加载项应用延迟
              });
              animation.opacity(1).translateY(0).step();
              
              this.setData({
                [`comments[${index}].animation`]: animation.export()
              });
            });
          }, 100);
        } else {
          wx.showToast({
            title: res.data.message || '获取数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
        console.error('获取评论列表失败:', err);
      },
      complete: () => {
        this.setData({ isLoading: false });
      }
    });
  },

  // 点赞评论
  likeComment: function(e) {
    const index = e.currentTarget.dataset.index;
    const comment = this.data.comments[index];
    const isLiked = comment.isLiked;
    
    // 添加触感反馈
    if (wx.vibrateShort) {
      wx.vibrateShort({ type: 'medium' });
    }
    
    // 先更新UI
    this.setData({
      [`comments[${index}].isLiked`]: !isLiked
    });
    
    // API调用，实际项目中应该调用后端
    // wx.request({ ... })
    
    // 显示提示
    wx.showToast({
      title: isLiked ? '已取消点赞' : '点赞成功',
      icon: 'success',
      duration: 1500
    });
    
    // 阻止事件冒泡
    e.stopPropagation();
  },

  // 回复评论
  replyComment: function(e) {
    const index = e.currentTarget.dataset.index;
    const comment = this.data.comments[index];
    
    // 添加触感反馈
    if (wx.vibrateShort) {
      wx.vibrateShort({ type: 'medium' });
    }
    
    // 跳转到帖子详情页并自动聚焦评论框
    wx.navigateTo({
      url: `/pages/details/details?id=${comment.post.id}&focus=reply&replyTo=${comment.user.id}`
    });
    
    // 阻止事件冒泡
    e.stopPropagation();
  },

  // 跳转到帖子详情
  goToPost: function(e) {
    const postId = e.currentTarget.dataset.postId;
    wx.navigateTo({
      url: `/pages/details/details?id=${postId}`
    });
  },

  // 跳转到用户主页
  goToUser: function(e) {
    const userId = e.currentTarget.dataset.userId;
    wx.navigateTo({
      url: `/pages/user/user?userId=${userId}`
    });
    
    // 阻止事件冒泡
    e.stopPropagation();
  },

  // 简化的时间显示
  getSimpleDate: function(timestamp) {
    if (!timestamp) return '';
    
    const now = new Date();
    const date = new Date(timestamp);
    const diff = Math.floor((now - date) / 1000); // 秒数差
    
    if (diff < 60) {
      return '刚刚';
    } else if (diff < 3600) {
      return `${Math.floor(diff / 60)}分钟前`;
    } else if (diff < 86400) {
      return `${Math.floor(diff / 3600)}小时前`;
    } else if (diff < 604800) {
      return `${Math.floor(diff / 86400)}天前`;
    } else {
      // 超过7天显示具体日期
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${month}-${day}`;
    }
  }
}); 